import React from 'react';
import { inject, observer } from 'mobx-react';
import { WeaTableNew, WeaLogView } from 'comsMobx';

let WeaTable = WeaTableNew.WeaTable;
import {
  WeaTop,
  WeaTab,
  WeaLeftTree,
  WeaLeftRightLayout,
  WeaRightMenu,
  WeaErrorPage,
  WeaTools,
  WeaDialog,
  WeaCheckbox,
  WeaPopoverHrm,
  WeaLocaleProvider,
} from 'ecCom';
import { Button } from 'antd';
import PageSpin from '../public/PageSpin';
import NoViewRightPage from '../public/NoViewRightPage';
import CoworkConstant from '../util/CoworkConstant';
import * as CoworkUtil from '../util/CoworkUtil';
import { toJS } from 'mobx';

const getLabel = WeaLocaleProvider.getLabel;
const WeaLogViewComp = WeaLogView.Component;
const { viewer } = WeaTools;

/**
 * 内容监控
 */
@inject('coworkDiscussMonitorStore')
@observer
class DiscussMonitor extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showLog: false,
      targetId: '',
    };
  }

  componentDidMount() {
    this.props.coworkDiscussMonitorStore.doInit();
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.location.key !== nextProps.location.key) {
      this.props.coworkDiscussMonitorStore.doInit();
    }
  }

  componentWillUnmount() {
    // 组件卸载时一般清理一些状态
    const { coworkDiscussMonitorStore } = this.props;
    coworkDiscussMonitorStore.setSelectedKey(0);
    coworkDiscussMonitorStore.clearStatus();
  }

  render() {
    const { coworkDiscussMonitorStore } = this.props;
    const {
      viewRightInitCompleted,
      viewRight,
      comsWeaTableStore,
      loading,
      form,
      topTab,
      selectedKey,
      showSearchAd,
      sessionkey,
      deleteDialogVisible,
      logStore,
      status,
    } = coworkDiscussMonitorStore;
    const { logType, logSmallType } = toJS(status);

    if (!viewRightInitCompleted) {
      return (
        <PageSpin
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_PageSpin@uheghq`}
        />
      );
    } else if (!viewRight) {
      return (
        <NoViewRightPage
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_NoViewRightPage@qj0c41`}
        />
      );
    }

    const buttons = [
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@rcuoev@onok`}
        type="primary"
        onClick={this.executeDeleteOk}
      >
        {getLabel(83446, '确定')}
      </Button>,
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@8oneg7@cancel`}
        type="ghost"
        onClick={this.closeDeleteDialog}
      >
        {getLabel(201, '取消')}
      </Button>,
    ];
    let conditioninfo = this.getPageCondition();
    const buttonsAd = [
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@s5rq5a@search`}
        type="primary"
        onClick={this.onTabSearch}
      >
        {getLabel(197, '搜索')}
      </Button>,
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@5ajc2v@reset`}
        type="ghost"
        onClick={this.onTabReset}
      >
        {getLabel(2022, '重置')}
      </Button>,
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@uzk5qv@cancel`}
        type="ghost"
        onClick={this.onTabCancel}
      >
        {getLabel(201, '取消')}
      </Button>,
    ];

    return (
      <div className="wea-cowork-discussManage">
        <WeaPopoverHrm
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaPopoverHrm@pqeren`}
        />

        <WeaRightMenu
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaRightMenu@z69ofr`}
          datas={this.getRightMenu()}
          onClick={this.onRightMenuClick}
        >
          <WeaTop
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_WeaTop@vfc7ds`}
            title={getLabel(32577, '内容监控')}
            loading={loading}
            icon={CoworkConstant.icon}
            iconBgcolor={CoworkConstant.iconBgColor}
            buttonSpace={10}
            showDropIcon={true}
            dropMenuDatas={this.getRightMenu()}
            onDropMenuClick={this.onRightMenuClick}
            buttons={this.getTopButtons()}
          >
            <WeaLeftRightLayout
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_WeaLeftRightLayout@nlhb9i`}
              isNew={true}
              showLeft={false}
              leftCom={this.getLeftTree()}
            >
              <WeaTab
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_WeaTab@iggii3`}
                datas={topTab}
                keyParam="groupid"
                onChange={this.changeTab}
                selectedKey={selectedKey}
                searchType={['base', 'advanced']}
                searchsBaseValue={
                  selectedKey == 0
                    ? form.isFormInit &&
                      form.getFormParams() &&
                      form.getFormParams().remark
                    : form.isFormInit &&
                      form.getFormParams() &&
                      form.getFormParams().remarkBack
                }
                setShowSearchAd={this.setShowSearchAd}
                showSearchAd={showSearchAd}
                hideSearchAd={this.hideSearchAd}
                searchsAd={CoworkUtil.getSearchs(form, conditioninfo, () => {
                  coworkDiscussMonitorStore.setShowSearchAd(false);
                  coworkDiscussMonitorStore.doTableLoading();
                })}
                buttonsAd={buttonsAd}
                onSearch={coworkDiscussMonitorStore.doTableLoading}
                onSearchChange={this.onSearchChange}
              />
              <WeaTable
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_WeaTable@kphprh`}
                comsWeaTableStore={comsWeaTableStore}
                loading={loading}
                sessionkey={sessionkey}
                needScroll={true}
                hasOrder={true}
                getColumns={this.getNewColumns}
                onOperatesClick={this.onOperatesClick}
              />
            </WeaLeftRightLayout>
          </WeaTop>

          <WeaDialog
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_WeaDialog@qlvz1l`}
            visible={deleteDialogVisible}
            buttons={buttons}
            title={getLabel(131329, '信息确认')}
            style={{ width: 375, height: 100 }}
            onCancel={this.closeDeleteDialog}
          >
            <div
              style={{
                position: 'relative',
                textAlign: 'center',
                paddingTop: '25px',
              }}
            >
              <p style={{ height: '30px' }}>
                {getLabel(4041, '确定删除选定的信息吗？', 'note')}
              </p>
              <p>
                <WeaCheckbox
                  ecId={`${
                    (this && this.props && this.props.ecId) || ''
                  }_WeaCheckbox@nasulb`}
                  fieldName="isDeleteAll"
                  value={true}
                  viewAttr={2}
                  onChange={this.onCheckboxChange}
                />
                <span className="ml5">
                  {getLabel(385114, '删除此内容的所有评论')}
                </span>
              </p>
            </div>
          </WeaDialog>
        </WeaRightMenu>

        <WeaLogViewComp
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaLogViewComp@1bw00x`}
          visible={this.state.showLog}
          onCancel={this.onLogViewCancel}
          logStore={logStore}
          logType={logType}
          logSmallType={logSmallType}
          targetId={this.state.targetId}
        />
      </div>
    );
  }

  setShowSearchAd = (bool) => {
    this.props.coworkDiscussMonitorStore.setShowSearchAd(bool);
  };
  hideSearchAd = () => {
    this.props.coworkDiscussMonitorStore.setShowSearchAd(false);
  };
  onSearchChange = (v) => {
    const {
      coworkDiscussMonitorStore: { selectedKey, appendFormFields },
    } = this.props;
    selectedKey == 0
      ? appendFormFields({ remark: v })
      : appendFormFields({
          remarkBack: v,
        });
  };
  onCheckboxChange = (value) => {
    this.props.coworkDiscussMonitorStore.setIsDeleteAll(value);
  };
  onLogViewCancel = () => this.setState({ showLog: false });
  onSearchLabelClick = () => {
    const { coworkDiscussMonitorStore } = this.props;
    coworkDiscussMonitorStore.setSelectedTreeKeys([]);
    coworkDiscussMonitorStore.clearFormFields();
    coworkDiscussMonitorStore.doTableLoading();
  };
  onTreeSelect = (treeKey) => {
    const { coworkDiscussMonitorStore } = this.props;
    let key = treeKey.substring(treeKey.indexOf('_') + 1);
    if (treeKey.indexOf('cMainType_') != -1) {
      // 类别
      coworkDiscussMonitorStore.clearFormFields();
    } else if (treeKey.indexOf('cType_') != -1) {
      // 版块
      coworkDiscussMonitorStore.setFormFields({ typeid: key }); // 设置高级查询条件的版块条件
    }
    coworkDiscussMonitorStore.setSelectedTreeKeys([treeKey]);
    coworkDiscussMonitorStore.setShowSearchAd(false);
    coworkDiscussMonitorStore.doTableLoading();
  };

  // 左侧树
  getLeftTree() {
    const { coworkDiscussMonitorStore } = this.props;
    const {
      selectedTreeKeys,
      leftTreeDatas,
      leftTreeTypes,
      leftTreeCounts,
    } = toJS(coworkDiscussMonitorStore);
    return (
      <WeaLeftTree
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_WeaLeftTree@886n0h`}
        datas={leftTreeDatas}
        counts={leftTreeCounts}
        countsType={leftTreeTypes}
        selectedKeys={selectedTreeKeys}
        onSearchLabelClick={this.onSearchLabelClick}
        onSelect={this.onTreeSelect}
      />
    );
  }

  // 打开删除对话框
  openDeleteDialog = (discussIds) => {
    const { coworkDiscussMonitorStore } = this.props;
    coworkDiscussMonitorStore.showDeleteDialog(true, discussIds);
  };

  // 删除对话框，确定按钮事件
  executeDeleteOk = () => {
    const { coworkDiscussMonitorStore } = this.props;
    const { discussIds, isDeleteAll } = coworkDiscussMonitorStore.formValus;

    let reloadTable = this.executeSearch;
    let closeDeleteDialog = this.closeDeleteDialog;

    coworkDiscussMonitorStore.batchDiscussDel(
      {
        discussIds,
        isDeleteAll, // 是否同时删除所有评论
      },
      () => {
        closeDeleteDialog();
        reloadTable();
      },
    );
  };

  // 关闭删除对话框的回调
  closeDeleteDialog = () => {
    const { coworkDiscussMonitorStore } = this.props;
    coworkDiscussMonitorStore.showDeleteDialog(false);
  };

  // 切换tab事件
  changeTab = (theKey) => {
    const { coworkDiscussMonitorStore } = this.props;

    coworkDiscussMonitorStore.setSelectedKey(theKey);

    let conditioninfo = this.getPageCondition();
    coworkDiscussMonitorStore.reinitializeForm(conditioninfo);

    this.executeSearch();
  };

  // top中的按钮
  getTopButtons() {
    const { coworkDiscussMonitorStore } = this.props;
    const { selectedKey } = coworkDiscussMonitorStore;

    const buttons = [];
    if (selectedKey == 0) {
      let _disabled = !this.getTableSelectedValues().length;
      buttons.push(
        <Button
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_Button@haq83q@delete`}
          type="primary"
          disabled={_disabled}
          onClick={this.discussDelete}
        >
          {getLabel(32136, '批量删除')}
        </Button>,
      );
    }
    return buttons;
  }

  // 右键菜单
  getRightMenu() {
    const { coworkDiscussMonitorStore } = this.props;
    const { selectedKey } = toJS(coworkDiscussMonitorStore);

    let _disabled = !this.getTableSelectedValues().length;

    let btns = [];
    btns.push({
      key: 'search',
      icon: <i className="icon-coms-search" />,
      content: getLabel(197, '搜索'),
    });

    if (selectedKey && selectedKey == 0) {
      btns.push({
        key: 'discussDelete',
        icon: <i className="icon-coms-Custom" />,
        content: getLabel(32136, '批量删除'),
        disabled: _disabled,
      });
    }
    btns.push({
      key: 'BTN_LOG',
      icon: <i className="icon-coms-Print-log" />,
      content: `${getLabel(83, '日志')}`,
      onClick: () => this.onRightMenuClick('BTN_LOG'),
    });
    btns.push({
      key: 'ShowCustomColumns',
      icon: <i className="icon-coms-Custom" />,
      content: getLabel(382660, '显示定制列'),
    });
    /*
		btns.push({ key: "collection", icon: <i className='icon-coms-Custom'/>, content: '收藏' });
		btns.push({ key: "help", icon: <i className='icon-coms-Custom'/>, content: '帮助' });
		*/
    return btns;
  }

  // 右键菜单事件绑定
  onRightMenuClick = (key) => {
    const { coworkDiscussMonitorStore } = this.props;
    if (key == 'search') {
      this.executeSearch();
    } else if (key == 'discussDelete') {
      this.discussDelete();
    } else if (key == 'BTN_LOG') {
      this.setState({ showLog: true });
    } else if (key == 'ShowCustomColumns') {
      const { sessionkey, comsWeaTableStore } = coworkDiscussMonitorStore;
      comsWeaTableStore.setColSetVisible(sessionkey, true);
      comsWeaTableStore.tableColSet(sessionkey, true);
    }
  };

  // 执行搜索方法（也可用于刷新table）
  executeSearch = () => {
    const { coworkDiscussMonitorStore } = this.props;
    coworkDiscussMonitorStore.setShowSearchAd(false);
    coworkDiscussMonitorStore.doTableLoading();
  };

  discussDelete = () => {
    this.executeButtonMethod('discussDelete');
  };
  executeButtonMethod(type, values) {
    if (!values) {
      values = this.getTableSelectedValues();
    }
    switch (type) {
      case 'discussDelete': {
        this.openDeleteDialog(values);
        break;
      }
    }
  }

  // 获得table选中行的主键值数组。若没选中任何一条，返回空数组
  getTableSelectedValues() {
    const { coworkDiscussMonitorStore } = this.props;
    const { comsWeaTableStore } = coworkDiscussMonitorStore;
    let values = comsWeaTableStore.selectedRowKeysAllPages;
    return values;
  }

  getPageCondition() {
    const { coworkDiscussMonitorStore } = this.props;
    const { selectedKey, conditioninfo } = toJS(coworkDiscussMonitorStore);
    if (conditioninfo && conditioninfo.length > 0) {
      return conditioninfo[selectedKey];
    }
    return [];
  }

  onTabSearch = () => {
    const { coworkDiscussMonitorStore } = this.props;
    coworkDiscussMonitorStore.setShowSearchAd(false);
    coworkDiscussMonitorStore.doTableLoading();
  };
  onTabReset = () => {
    const { coworkDiscussMonitorStore } = this.props;
    coworkDiscussMonitorStore.clearFormFields();
  };
  onTabCancel = () => {
    const { coworkDiscussMonitorStore } = this.props;
    coworkDiscussMonitorStore.setShowSearchAd(false);
  };

  onRemarkClick = (e) => {
    if (e.target.nodeName === 'IMG') {
      let img = e.target;
      img.setAttribute('data-imgsrc', img.src);
      img.setAttribute('class', 'formImgPlay');
      viewer(e);
    }
  };

  // 自定义过滤渲染
  getNewColumns = (columns) => {
    let newColumns = '';
    newColumns = columns.map((column) => {
      let newColumn = column;
      newColumn.render = (text, record) => {
        // 前端元素转义
        let valueSpan =
          record[`${newColumn.dataIndex}span`] !== undefined
            ? record[`${newColumn.dataIndex}span`]
            : record[newColumn.dataIndex];
        let url = '';
        if (newColumn.dataIndex == 'coworkid') {
          url = CoworkUtil.getViewCoworkUrl(record.coworkid);
        } else if (newColumn.dataIndex == 'floorNum') {
          url = CoworkUtil.getViewCoworkOfFloorNnmUrl(
            record.coworkid,
            record.floorNum,
          );
        }
        if (
          newColumn.dataIndex === 'remark' ||
          newColumn.dataIndex === 'remarkBack'
        ) {
          return (
            <div
              className={'cowork-tablename-remark wea-url'}
              dangerouslySetInnerHTML={{ __html: valueSpan }}
              onClick={this.onRemarkClick}
            />
          );
        }

        return url == '' ? (
          <div
            className="wea-url"
            dangerouslySetInnerHTML={{ __html: valueSpan }}
          />
        ) : (
          <div
            className="wea-url-name"
            dangerouslySetInnerHTML={{ __html: valueSpan }}
            style={{ cursor: 'pointer' }}
            title={text}
            onClick={() => {
              window.open(url);
            }}
          />
        );
      };
      return newColumn;
    });
    return newColumns;
  };

  // 表格单元格转义
  onOperatesClick = (record, index, operate, flag) => {
    let discussId = record.id;
    if (flag == 0) {
      // 删除
      this.executeButtonMethod('discussDelete', discussId);
    }
  };
}

export default WeaTools.tryCatch(
  React,
  props => (
    <WeaErrorPage
      ecId={`${
        (this && this.props && this.props.ecId) || ''
      }_WeaErrorPage@4mvmtb`}
      msg={
        props.error
          ? props.error
          : getLabel(186, '对不起，该页面异常，请联系管理员！', 'error')
      }
    />
  ),
  { error: '' },
)(DiscussMonitor);
